package com.cashmate.struts;

import com.cashmate.hibernate.dao.MatrixcategoriesDAO;
import com.cashmate.hibernate.pojo.Employees;
import com.cashmate.hibernate.pojo.Matrixcategories;
import com.cashmate.hibernate.pojo.Usertypes;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.ServletActionContext;

public class EditMatrixcategories extends ActionSupport {

    private static Logger logger = Logger.getLogger(EditMatrixcategories.class);
    //This properties have setters below... The setters are called and populated by the grid.
    private String oper; //add,edit,del
    private String categname;
    private String id;
    private String percentage;
    private MatrixcategoriesDAO mat = (MatrixcategoriesDAO) ServletActionContext.getServletContext().getAttribute("matrixcategoriesDAO");
    private Employees emps = (Employees) ServletActionContext.getRequest().getSession().getAttribute("employee");
    private Usertypes ut = (Usertypes) ServletActionContext.getRequest().getSession().getAttribute("usertype");

    //Notice we don't have a success result because we do not need to redirect the user when he/she updates the dbase
    //We redirect him/her only if an error occurred.
    @Action(value = "/edit-matrixcategory", results = {
        @Result(name = "invalid", location = "../error/formError.jsp"),
        @Result(name = "error", type = "redirectAction", location = "../error/messages.jsp")
    })
    @Override
    public String execute() throws Exception {
        Matrixcategories matrix;
        List<Matrixcategories> matrixList;
        try {
            //oper is populated by the grid, the "add","edit","del" strings are constant values.
            if (oper.equalsIgnoreCase("add")) {
                int percent = Integer.parseInt(percentage);
                int total = 0;
                matrixList = mat.getAll();
                for (Matrixcategories m : matrixList) {
                    if (m.isIsactive()) {
                        if (categname.equalsIgnoreCase(m.getCategname())) {
                            addActionError("ERROR : Category:" + m.getCategname() + ". Already exist.");
                            return "invalid";
                        }
                        total += m.getPercentage();
                    }
                }
                total += percent;
                if (total > 100) {
                    addActionError("ERROR : Percentage is:" + total + "%. Please ensure the total percentage is lesser than or equal to 100%");
                    return "invalid";
                }
                matrix = new Matrixcategories(categname, percent, true);
                mat.insert(matrix);
                logger.info(ut.getType() + " (" + emps.getIdnumber() + ") added matrix category{categname:" + matrix.getCategname() + ", percentage:" + matrix.getPercentage() + "}");

            } else if (oper.equalsIgnoreCase("edit")) {
                matrix = mat.get(Integer.parseInt(id));
                String old = matrix.getCategname();
                int percent = Integer.parseInt(percentage);
                int total = 0;
                matrixList = mat.getAll();
                if (matrix.getPercentage() != percent) {
                    for (Matrixcategories m : matrixList) {
                        if (m.isIsactive() && m.getMatrixcategid() != matrix.getMatrixcategid()) {
                            if (categname.equalsIgnoreCase(m.getCategname())) {
                                addActionError("ERROR : Category:" + m.getCategname() + ". Already exist.");
                                return "invalid";
                            }
                            total += m.getPercentage();
                        }
                    }
                    total += percent;
                    if (total > 100) {
                        addActionError("ERROR : Percentage is:" + total + "%. Please ensure the total percentage is lesser than or equal to 100%");
                        return "invalid";
                    }
                }
                matrix.setCategname(categname);
                matrix.setPercentage(percent);
                mat.update(matrix);
                logger.info(ut.getType() + " (" + emps.getIdnumber() + ") updated matrix category(" + old + ") with new values{categname:" + matrix.getCategname() + ", percentage:" + matrix.getPercentage() + "}");
            } else if (oper.equalsIgnoreCase("del")) {
                matrix = mat.get(Integer.parseInt(id));
                matrix.setIsactive(false);
                mat.update(matrix);
                logger.info(ut.getType() + " (" + emps.getIdnumber() + ") deleted matrix category(" + matrix.getCategname() + ")");
            }
        } catch (Exception e) {
            if (emps != null) {
                logger.fatal("(" + emps.getIdnumber() + "):" + e.getLocalizedMessage(), e);
            } else {
                logger.fatal(e.getLocalizedMessage(), e);
            }
            e.printStackTrace();
            addActionError(e.getLocalizedMessage());
            return ERROR;
        }
        return NONE;
    }

    public void setCategname(String categname) {
        this.categname = categname;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setOper(String oper) {
        this.oper = oper;
    }

    public void setPercentage(String percentage) {
        this.percentage = percentage;
    }
}
